//
//  ScenicCityListViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/10/31.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "ScenicCityListViewController.h"
#import "ScenicCityListModel.h"

@interface ScenicCityListViewController ()

@property (nonatomic, strong) NSMutableDictionary *allCityDic;
@property (nonatomic, strong) NSMutableArray *dicAllKeysArr;
@property (nonatomic, strong) DDIndicator *indicator;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) AppDelegate *app;

@end

@implementation ScenicCityListViewController
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadData" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _app = [[AppDelegate alloc] init];
    self.edgesForExtendedLayout = UIRectEdgeNone;
 self.view.backgroundColor = [UIColor whiteColor];
    
    [self addLoading];
    [self setUpData];
    [self freshHeader];
    [self setNavigationBar];
    [self addInternetObserver];
}
// 通知网络状态
- (void)addInternetObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithInternet:) name:@"reloadData" object:nil];
}

- (void)reloadDataWithInternet:(NSNotification *)notification
{
    [self setUpData];
}



- (void)setNavigationBar
{
  self.navigationItem.title = @"城市列表";
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backNew.png"] style:(UIBarButtonItemStylePlain) target:self action:@selector(actionLeftButton:)];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}

- (void)actionLeftButton:(UIBarButtonItem *)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewWillAppear:(BOOL)animated
{
    
}

- (void)freshHeader
{
    if ([_app internetReachableOrNot]) {
    self.tableView.header = [LYBAnimationHeader headerWithRefreshingTarget:self refreshingAction:@selector(setUpData)];
   // [self.tableView.header beginRefreshing];
    } else {
        [self alertController];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.dicAllKeysArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *key = self.dicAllKeysArr[section];
    NSMutableArray *dataArray = [self.allCityDic valueForKey:key];
    return dataArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"ScenicCityList";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier] ;
    }
    if (self.dicAllKeysArr.count > 0) {
        NSString *key = self.dicAllKeysArr[indexPath.section];
        NSMutableArray *tempArray = [self.allCityDic valueForKey:key];
        ScenicCityListModel *model = tempArray[indexPath.row];
        cell.textLabel.text= model.Name;
    }
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.dicAllKeysArr.count > 0) {
        return self.dicAllKeysArr[section];
    }
    
    return @"";
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.dicAllKeysArr;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *key = self.dicAllKeysArr[indexPath.section];
    NSMutableArray *tempArray = [self.allCityDic valueForKey:key];
    ScenicCityListModel *model = tempArray[indexPath.row];
    [_delegate reloadDatById:model.Id cityName:model.Name];
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)setUpData
{
    if ([_app internetReachableOrNot]) {
   
    
    NSString *urlString = [NSString stringWithFormat:@"http://webapi.yilule.com:5580//api/TourData?scaleType=2"];
    
    NSString *url = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    [request setHTTPMethod:@"GET"];
    
    self.allCityDic = [NSMutableDictionary dictionary];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
        } else {
            NSArray *tempArr = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            
            for (NSDictionary *dic in tempArr) {
                ScenicCityListModel *model = [[ScenicCityListModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                NSString *group = [model.Pinyin substringToIndex:1];
                NSMutableArray *valueArray = [self.allCityDic valueForKey:group];
                if (valueArray == nil) {
                    // 如果为空说明没有这对键值 需要创建并添加
                    valueArray = [NSMutableArray array];
                    
                    [self.allCityDic setValue:valueArray forKey:group];
                } else if (valueArray != nil) {
                    // 说明有着个数组 判断是否重名 如果没重名就添加
                    for (int i = 0; i < valueArray.count; i++) {
                        ScenicCityListModel *tempModel = valueArray[i];
                        if ([tempModel.Name isEqualToString:model.Name]) {
                            [valueArray removeObject:tempModel];
                        }
                    }
                }
                [[self.allCityDic valueForKey:group] addObject:model];
            }
            self.dicAllKeysArr = [NSMutableArray arrayWithArray:[self.allCityDic allKeys]];
            [self.dicAllKeysArr sortUsingSelector:@selector(compare:)];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView.header endRefreshing];
                 [self StopLoading];
                [self.tableView reloadData];
               
            });
        }
    }];
    [dataTask resume];
    } else {
        [self alertController];
    }
}

- (void)alertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的当前网络中断或网络信号差, 请检查网络后重新进入!!" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}


#pragma mark -- 等待动画
- (void)addLoading
{
    // 添加等待动画
    
    self.bgView.hidden = NO;
    
    [self.tableView addSubview:self.bgView];
    
    self.indicator = [[DDIndicator alloc] initWithFrame:CGRectMake((self.bgView.width - 40) / 2, (self.bgView.height - 40) / 2, 40, 40)];
    [self.bgView addSubview:self.indicator];
    
    [self.indicator startAnimating];
}

- (void)StopLoading
{
    self.bgView.hidden = YES;
    [self.indicator stopAnimating];
}


#pragma mark -- bgView的懒加载
- (UIView *)bgView
{
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake((self.tableView.width - 100) / 2, (self.tableView.height - 100) / 2, 100, 100)];
        _bgView.backgroundColor = [UIColor whiteColor];
    }
    return _bgView;
}


@end
